package com.nodecollege.cloud.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.nodecollege.cloud.common.UpmsConstants;
import com.nodecollege.cloud.common.constants.NCConstants;
import com.nodecollege.cloud.common.exception.UpmsException;
import com.nodecollege.cloud.common.model.NCResult;
import com.nodecollege.cloud.common.model.QueryVO;
import com.nodecollege.cloud.common.model.po.*;
import com.nodecollege.cloud.common.utils.NCUtils;
import com.nodecollege.cloud.common.utils.RegularExpUtils;
import com.nodecollege.cloud.dao.mapper.*;
import com.nodecollege.cloud.service.UserInvitationService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 邀请用户
 *
 * @author LC
 * @date 2019/12/12 18:15
 */
@Service
public class UserInvitationServiceImpl implements UserInvitationService {

    @Autowired
    private UpmsMemberMapper upmsMemberMapper;

    @Autowired
    private UpmsUserMapper upmsUserMapper;

    @Autowired
    private UpmsUserInvitationMapper upmsUserInvitationMapper;

    @Autowired
    private UpmsRoleMapper upmsRoleMapper;

    @Autowired
    private UpmsOrgMapper upmsOrgMapper;

    @Autowired
    private UpmsOrgMemberMapper upmsOrgMemberMapper;

    @Autowired
    private UpmsRoleMemberMapper upmsRoleMemberMapper;

    /**
     * 查询邀请列表
     *
     * @param queryVO
     */
    @Override
    public NCResult<UpmsUserInvitation> getInvitedList(QueryVO<UpmsUserInvitation> queryVO) {
        List<UpmsUserInvitation> list = new ArrayList<>();
        Long total = 0L;
        if (NCConstants.INT_NEGATIVE_1.equals(queryVO.getPageSize())) {
            list = upmsUserInvitationMapper.selectListByMap(queryVO.toMap());
            total = NCUtils.isNullOrEmpty(list) ? 0 : Long.parseLong(list.size() + "");
        } else {
            Page page = PageHelper.startPage(queryVO.getPageNum(), queryVO.getPageSize());
            if (queryVO.isSort()) {
                page.setOrderBy(queryVO.getSortKey() + " " + queryVO.getSortDirection());
            }
            list = upmsUserInvitationMapper.selectListByMap(queryVO.toMap());
            total = page.getTotal();
        }
        return NCResult.ok(list, total);
    }

    /**
     * 邀请用户
     *
     * @param upmsUserInvitation
     */
    @Override
    public void inviteMember(UpmsUserInvitation upmsUserInvitation) {
        NCUtils.nullOrEmptyThrow(upmsUserInvitation.getInvitedUserTelephone(), new UpmsException("-1", "待邀请账号必填！"));
        if (!RegularExpUtils.checkTelephone(upmsUserInvitation.getInvitedUserTelephone())) {
            throw new UpmsException("-1", "电话密码格式不正确！");
        }

        // 检测该账号是否已经被邀请
        UpmsUserInvitation queryInvite = new UpmsUserInvitation();
        queryInvite.setInviteTenantId(upmsUserInvitation.getInviteTenantId());
        queryInvite.setInvitedUserTelephone(upmsUserInvitation.getInvitedUserTelephone());
        List<UpmsUserInvitation> exitList = upmsUserInvitationMapper.selectListByMap(new QueryVO<>(queryInvite).toMap());
        NCUtils.notNullOrNotEmptyThrow(exitList, new UpmsException("-1", "该账号已经被邀请！"));

        // 根据被邀请账号查询用户是否存在
        UpmsUser query = new UpmsUser();
        query.setTelephone(upmsUserInvitation.getInvitedUserTelephone());
        List<UpmsUser> users = upmsUserMapper.selectUserListByMap(new QueryVO<>(query).toMap());

        // 不为空直接添加成员信息
        if (NCUtils.isNotNullOrNotEmpty(users)) {
            UpmsUser user = users.get(0);

            // 查询该用户是否已经是该租户成员
            UpmsMember queryMember = new UpmsMember();
            queryMember.setUserId(user.getUserId());
            queryMember.setTenantId(upmsUserInvitation.getInviteTenantId());
            List<UpmsMember> exitMemberList = upmsMemberMapper.selectListByMap(new QueryVO<>(queryMember).toMap());
            NCUtils.notNullOrNotEmptyThrow(exitMemberList, new UpmsException("-1", "该用户已经是公司成员！"));

            addMember(user, upmsUserInvitation);
        } else {
            upmsUserInvitationMapper.insertSelective(upmsUserInvitation);
        }
    }

    /**
     * 校验是否被邀请
     * 被邀请 创建对应租户的成员信息
     * 返回租户id
     *
     * @param user
     */
    @Override
    public void checkInviteAndAddMember(UpmsUser user) {
        UpmsUserInvitation query = new UpmsUserInvitation();
        query.setInvitedUserTelephone(user.getTelephone());
        List<UpmsUserInvitation> exitList = upmsUserInvitationMapper.selectListByMap(new QueryVO<>(query).toMap());
        if (NCUtils.isNullOrEmpty(exitList)) {
            return;
        }
        // 添加成员信息
        exitList.forEach(item -> {
            addMember(user, item);
            // 移除邀请记录
            upmsUserInvitationMapper.deleteByPrimaryKey(item.getId());
            // 用户无租户信息，绑定租户信息
            if (user.getTenantId() == null) {
                UpmsUser updateUser = new UpmsUser();
                updateUser.setUserId(user.getUserId());
                updateUser.setTenantId(item.getInviteTenantId());
                upmsUserMapper.updateByPrimaryKeySelective(updateUser);
            }
        });
    }

    /**
     * 添加成员信息
     *
     * @param user
     * @param member
     */
    private void addMember(UpmsUser user, UpmsUserInvitation member) {
        UpmsMember upmsMember = new UpmsMember();
        upmsMember.setUserId(user.getUserId());
        String name = member.getInvitedUserName();
        upmsMember.setMemberName(StringUtils.isBlank(name) ? user.getAccount() : name);
        upmsMember.setTenantId(member.getInviteTenantId());
        upmsMember.setCreateTime(new Date());

        // 查询默认新成员组织机构
        UpmsOrg orgQuery = new UpmsOrg();
        orgQuery.setOrgCode(UpmsConstants.NEW_MEMBER_DEFALUT_ORG);
        orgQuery.setTenantId(member.getInviteTenantId());
        UpmsOrg newMemberOrg = upmsOrgMapper.selectListByMap(new QueryVO<>(orgQuery).toMap()).get(0);
        upmsMember.setDefaultOrgId(newMemberOrg.getOrgId());

        // 查询默认新成员角色
        UpmsRole roleQuery = new UpmsRole();
        roleQuery.setRoleCode(UpmsConstants.NEW_MEMBER_DEFALUT_ROLE);
        roleQuery.setTenantId(member.getInviteTenantId());
        roleQuery.setOrgId(NCConstants.LONG_0);
        UpmsRole newMemberRole = upmsRoleMapper.selectListByMap(new QueryVO<>(roleQuery).toMap()).get(0);
        upmsMember.setDefaultRoleId(newMemberRole.getRoleId());

        upmsMemberMapper.insertSelective(upmsMember);

        // 保存组织机构成员关系
        UpmsOrgMember orgMember = new UpmsOrgMember();
        orgMember.setMemberId(upmsMember.getMemberId());
        orgMember.setTenantId(member.getInviteTenantId());
        orgMember.setOrgId(newMemberOrg.getOrgId());
        upmsOrgMemberMapper.insert(orgMember);

        // 保存角色成员关系
//        UpmsRoleMember roleMember = new UpmsRoleMember();
//        roleMember.setMemberId(upmsMember.getMemberId());
//        roleMember.setTenantId(member.getInviteTenantId());
//        roleMember.setRoleId(newMemberRole.getRoleId());
//        roleMember.setState(NCConstants.INT_1);
//        upmsRoleMemberMapper.insert(roleMember);
    }
}
